<template>
  <div class="stats-container">
    <el-card shadow="never" v-loading="isLoading">
      <template #header>
        <div class="card-header">
          <span>考试统计 (ID: {{ examId }})</span>
          <el-button @click="goBack" style="margin-left: auto;">返回</el-button>
        </div>
      </template>

      <div v-if="errorMsg">
        <el-alert type="error" :title="errorMsg" show-icon :closable="false"></el-alert>
      </div>
      <div v-else-if="stats">
        <el-descriptions title="统计指标" :column="2" border>
          <el-descriptions-item label="总考生人数">{{ stats.totalStudents }}</el-descriptions-item>
          <el-descriptions-item label="完成人数">{{ stats.completed }}</el-descriptions-item>
          <el-descriptions-item label="通过人数">{{ stats.passed }}</el-descriptions-item>
          <el-descriptions-item label="平均分">{{ stats.averageScore?.toFixed(1) ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="通过率">{{ (stats.passRate * 100).toFixed(1) }}%</el-descriptions-item>
        </el-descriptions>
      </div>
      <el-empty v-else description="暂无统计数据"></el-empty>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElCard, ElDescriptions, ElDescriptionsItem, ElButton, ElAlert, ElEmpty } from 'element-plus';
import { getExamStatistics } from '@/services/examService';

const route = useRoute();
const router = useRouter();

const examId = ref(route.params.id);
const stats = ref(null);
const isLoading = ref(false);
const errorMsg = ref('');

const loadStats = async () => {
  if (!examId.value) {
    errorMsg.value = '无效的考试ID';
    return;
  }
  isLoading.value = true;
  try {
    const response = await getExamStatistics(examId.value);
    if (response && response.success && response.data) {
      stats.value = response.data;
    } else {
      errorMsg.value = response.message || '获取统计信息失败';
    }
  } catch (error) {
    console.error('Error fetching exam statistics:', error);
    errorMsg.value = '加载统计信息时发生错误';
  } finally {
    isLoading.value = false;
  }
};

const goBack = () => {
  router.back();
};

onMounted(() => {
  loadStats();
});
</script>

<style scoped>
.stats-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 